#ifndef CONNECT_H
#define CONNECT_H
#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QDebug>

//判断表是否存在
bool isTableExists(const QString &table)
{
    QSqlQuery query;
    QString sql = QString("select * from sqlite_master where name = '%1';").arg(table);  // 查询sqlite_master表中是否存在表名
    if(query.exec(sql))//如果存在返回第一个结果
    {
        return query.next();
    }
    return false;
}

static bool createConnection()//static：所有类共享的函数
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");//创建连接数据库实例
    db.setDatabaseName("userdatebase.db");
    if (!db.open())//没能成功建立用户数据库
    {
        QMessageBox::critical(0, qApp->tr("Cannot open database"), qApp->tr("Unable to establish a database connection."), QMessageBox::Cancel);
        return false;
    }
    if(!isTableExists("UserManagement"))
    {
        QSqlQuery query(db);//操作数据库的实例
        //创建一个表User，包含索引，用户名，密码，用户类型
        query.exec("create table UserManagement (id INTEGER PRIMARY KEY AUTOINCREMENT,name varchar(20),password varchar(20),type varchar(20))");
        // 调用插入数据的函数
        query.exec("insert into UserManagement values(0, 'root','123456','Root')");
        query.exec("insert into UserManagement values(1, 'adminqb-1','123456','Administrator')");
        query.exec("insert into UserManagement values(2, 'adminfs-1','123456','Administrator')");
        query.exec("insert into UserManagement values(3, 'adminfh-1','123456','Administrator')");
        query.exec("insert into UserManagement values(4, 'userqb-1','123456','User')");
        query.exec("insert into UserManagement values(5, 'userfs-1','123456','User')");
        query.exec("insert into UserManagement values(6, 'userfh-1','123456','User')");
        query.exec("insert into UserManagement values(7, 'admin','123456','Administrator')");
        query.exec("insert into UserManagement values(8, 'user','123456','User')");
//        query.prepare("insert into User(userName, password, type)"
//                      "values (:userName, :password, :type)");
//        query.bindValue(":userName", userName);
//        query.bindValue(":password", password);
//        query.bindValue(":type", int(userType));
//        query.exec();
        return true;
    }

    return false;
}

#endif // CONNECT_H
